package cn.com.zpark.jdbc;

import cn.com.zpark.jdbc.pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: cn.com.zpark.jdbc
 * @ClassName: JDBC_01_Select
 * @Description:
 * @author: RZS
 * @date: 2021/10/26  16:48
 */
public class JDBC_02_Select {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stat = null;
        ResultSet res = null;
        String url = "jdbc:mysql://192.168.80.142:3306/mydb2?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
        try {
            // 1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获取连接
            conn = DriverManager.getConnection(url, "root", "root");
            // 3、创建statement对象
            stat = conn.createStatement();
            // 4、编写sql
            String sql = "select * from user";
            // 5、执行sql
            res = stat.executeQuery(sql);
            // 创建集合list，用于存放user对象
            List<User> list = new ArrayList<>();
            // 6、获取查询结果
            while (res.next()) {
                // 创建user对象，存储查询结果
                User user = new User();
                user.setId(res.getInt("id"));
                user.setName(res.getString("name"));
                user.setPwd(res.getString("pwd"));
                user.setMoney(res.getDouble("money"));
                // 将user对象存放的集合中
                list.add(user);

            }
            System.out.println(list);
            for (User user : list) {
                System.out.println(user.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 7、关闭连接
            if(res != null){
                try {
                    res.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stat != null){
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
